<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";

const route = useRoute();
const router = useRouter();

// 订单接口定义 - 匹配后端结构
interface Order {
    id: number;
    material_id: number;
    client_id: number;
    contact_id: number;
    quantity: number;
    price: number;
    amount: number;
    unit: string;
    place_order_date: string;
    plan_delivery_date: string;
    actual_delivery_date: string | null;
    status: number;
    remark: string;
    image_path: string | null;
    created_at: string;
    created_by: string;
    modified_at: string;
    modified_by: string;
    customer_name: string | null;
    customer_code: string | null;
    material_name: string | null;
    material_code: string | null;
    contact_name: string | null;
}

// 公司接口定义
interface Company {
    id: number;
    name: string;
    type_id: number;
    status: number;
    address: string;
    contacts: string[];
    staff_num: number;
    capacity: string;
    remark: string;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
}

// 材料接口定义
interface Material {
    id: number | null;
    name: string | null;
    code: string | null;
    parent_id: number;
    supplier_id: number | null;
    color_code: string | null;
    background_material: string | null;
    status: number;
    length: number | null;
    width: number | null;
    thickness: number | null;
    residual: number | null;
    price: number | null;
    unit: string | null;
    remark: string | null;
    is_leaf: boolean | null;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
}

// 联系人接口（与后端Contact结构匹配）
interface Contact {
    id: number;
    name: string;
    email: string | null;
    phone: string | null;
    gender: number | null;
    birthday: string | null;
    job_title: string | null;
    avatar: string | null;
    company_id: number | null;
    status: number;
    personality: string | null;
    company_name: string | null;
    created_at: string;
    created_by: string;
    modified_at: string;
    modified_by: string;
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 分页响应接口
interface PaginationResponse<T> {
    list: T[];
    total: number;
    page_current: number;
    page_size: number;
}

// 响应数据
const order = ref<Order>(createEmptyOrder());
const companies = ref<Company[]>([]);
const contacts = ref<Contact[]>([]);
const materials = ref<Material[]>([]);

// UI状态
const isEditMode = ref(false);
const loading = ref(false);
const error = ref("");
const success = ref("");
const showDeleteConfirm = ref(false);

// 搜索相关状态 - 确保所有变量都正确初始化
const companySearchText = ref("");
const contactSearchText = ref("");
const materialSearchText = ref("");
const showCompanyDropdown = ref(false);
const showContactDropdown = ref(false);
const showMaterialDropdown = ref(false);
const filteredCompanies = ref<Company[]>([]); // 确保初始化为空数组
const filteredContacts = ref<Contact[]>([]); // 确保初始化为空数组
const filteredMaterials = ref<Material[]>([]); // 确保初始化为空数组
const companyLoading = ref(false);
const contactLoading = ref(false);
const materialLoading = ref(false);

// 防抖计时器
let searchDebounceTimer: number | null = null;

// 选中的对象
const selectedCompany = ref<Company | null>(null);
const selectedMaterial = ref<Material | null>(null);
const selectedContact = ref<Contact | null>(null);

// 状态选项
const statusOptions = [
    { value: 0, label: "作废" },
    { value: 1, label: "意向订单" },
    { value: 2, label: "已审核" },
    { value: 3, label: "排期" },
    { value: 4, label: "生产计划" },
    { value: 5, label: "生产中" },
    { value: 6, label: "生产完成未检查" },
    { value: 7, label: "生产完成未发货" },
    { value: 8, label: "已发货" },
    { value: 9, label: "投诉处理" },
    { value: 10, label: "完成" },
    { value: 11, label: "客户取消" },
    { value: 12, label: "退货" },
    { value: 13, label: "退货完成" },
    { value: 14, label: "索赔" },
];

// 单位选项
const unitOptions = [
    { value: "美元", label: "美元" },
    { value: "人民币元", label: "人民币元" },
    { value: "欧元", label: "欧元" },
];

// 公司类型选项
const companyTypeOptions = [
    { value: 1, label: "材料生产单位" },
    { value: 2, label: "供应商" },
    { value: 3, label: "其他服务型" },
];

// 公司状态选项
const companyStatusOptions = [
    { value: 1, label: "正常" },
    { value: 2, label: "停业" },
    { value: 3, label: "注销" },
];

// 联系人状态选项
const contactStatusOptions = [
    { value: 0, label: "离职" },
    { value: 1, label: "在职" },
    { value: 2, label: "试用期" },
    { value: 3, label: "退休" },
];

// 获取订单ID
const orderId = computed(() => {
    return route.params.id ? parseInt(route.params.id as string) : null;
});

// 创建空订单对象
function createEmptyOrder(): Order {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const now = `${year}-${month}-${day}`;

    return {
        id: 0,
        material_id: 0,
        client_id: 0,
        contact_id: 0,
        quantity: 0,
        price: 0,
        amount: 0,
        unit: "美元",
        place_order_date: now,
        plan_delivery_date: now,
        actual_delivery_date: null,
        status: 1, // 默认意向订单
        remark: "",
        image_path: null,
        created_at: "",
        created_by: "",
        modified_at: "",
        modified_by: "",
        customer_name: "",
        customer_code: "",
        material_name: "",
        material_code: "",
        contact_name: "",
    };
}

// 计算总价
const totalAmount = computed(() => {
    const amount = order.value.quantity * (order.value.price / 10000);
    order.value.amount = Math.round(amount * 10000);
    return amount.toFixed(2);
});

// 价格处理函数
function setPrice(value: number) {
    order.value.price = Math.round(value * 10000);
}

function getDisplayPrice() {
    if (!order.value.price) return 0;
    return order.value.price / 10000;
}

// 获取公司列表（用于初始加载）
async function fetchCompanies() {
    try {
        const response: ApiResponse<Company[]> = await invoke(
            "list_company_by_name",
            {
                name: null,
            },
        );
        if (response.status_code === 200 && response.data) {
            companies.value = response.data;
        } else {
            console.error("获取公司列表失败:", response.message);
        }
    } catch (err) {
        console.error("获取公司列表失败:", err);
    }
}

// 获取材料列表
async function fetchMaterials() {
    try {
        const response: ApiResponse<Material[]> = await invoke(
            "list_materials_by_code",
            {
                material_code: null,
            },
        );
        if (response.status_code === 200 && response.data) {
            materials.value = response.data;
        } else {
            console.error("获取材料列表失败:", response.message);
        }
    } catch (err) {
        console.error("获取材料列表失败:", err);
    }
}

// 获取联系人列表
async function fetchContactsByCompany(companyId: number) {
    try {
        const response: ApiResponse<Contact[]> = await invoke(
            "list_contact_by_company",
            {
                company_id: companyId,
            },
        );
        if (response.status_code === 200 && response.data) {
            contacts.value = response.data;
        } else {
            console.error("获取联系人列表失败:", response.message);
            contacts.value = [];
        }
    } catch (err) {
        console.error("获取联系人列表失败:", err);
        contacts.value = [];
    }
}

// 公司搜索处理（带防抖）- 使用新的 list_company_by_name 接口
async function handleCompanySearch() {
    if (searchDebounceTimer) {
        clearTimeout(searchDebounceTimer);
    }

    searchDebounceTimer = setTimeout(async () => {
        const searchText = companySearchText.value.trim();

        if (searchText === "") {
            filteredCompanies.value = [];
            showCompanyDropdown.value = false;
            return;
        }

        companyLoading.value = true;
        showCompanyDropdown.value = true;

        try {
            const response: ApiResponse<Company[]> = await invoke(
                "list_company_by_name",
                {
                    name: searchText,
                },
            );

            if (response.status_code === 200 && response.data) {
                filteredCompanies.value = response.data;
            } else {
                console.error("搜索公司失败:", response.message);
                filteredCompanies.value = [];
            }
        } catch (err) {
            console.error("调用公司搜索API失败:", err);
            filteredCompanies.value = [];
            error.value = "搜索公司失败，请稍后重试";
        } finally {
            companyLoading.value = false;
        }
    }, 300);
}

// 联系人搜索处理（带防抖）
async function handleContactSearch() {
    if (!selectedCompany.value) {
        error.value = "请先选择客户";
        return;
    }

    if (searchDebounceTimer) {
        clearTimeout(searchDebounceTimer);
    }

    searchDebounceTimer = setTimeout(async () => {
        const searchText = contactSearchText.value.trim();

        if (searchText === "") {
            filteredContacts.value = [];
            showContactDropdown.value = false;
            return;
        }

        contactLoading.value = true;
        showContactDropdown.value = true;

        try {
            const response: ApiResponse<Contact[]> = await invoke(
                "list_contact_by_company",
                {
                    company_id: selectedCompany.value.id,
                },
            );

            if (response.status_code === 200 && response.data) {
                // 前端过滤联系人
                filteredContacts.value = response.data.filter(
                    (contact) =>
                        contact.name
                            .toLowerCase()
                            .includes(searchText.toLowerCase()) ||
                        (contact.phone && contact.phone.includes(searchText)) ||
                        (contact.email &&
                            contact.email
                                .toLowerCase()
                                .includes(searchText.toLowerCase())),
                );
            } else {
                console.error("搜索联系人失败:", response.message);
                filteredContacts.value = [];
            }
        } catch (err) {
            console.error("调用联系人搜索API失败:", err);
            filteredContacts.value = [];
            error.value = "搜索联系人失败，请稍后重试";
        } finally {
            contactLoading.value = false;
        }
    }, 300);
}

// 材料搜索处理（带防抖）
async function handleMaterialSearch() {
    if (searchDebounceTimer) {
        clearTimeout(searchDebounceTimer);
    }

    searchDebounceTimer = setTimeout(async () => {
        const searchText = materialSearchText.value.trim();

        if (searchText === "") {
            filteredMaterials.value = [];
            showMaterialDropdown.value = false;
            return;
        }

        materialLoading.value = true;
        showMaterialDropdown.value = true;

        try {
            const response: ApiResponse<Material[]> = await invoke(
                "list_materials_by_code",
                {
                    material_code: searchText,
                },
            );

            if (response.status_code === 200 && response.data) {
                filteredMaterials.value = response.data;
            } else {
                console.error("搜索材料失败:", response.message);
                filteredMaterials.value = [];
            }
        } catch (err) {
            console.error("调用材料搜索API失败:", err);
            filteredMaterials.value = [];
            error.value = "搜索材料失败，请稍后重试";
        } finally {
            materialLoading.value = false;
        }
    }, 300);
}

// 隐藏下拉框
function hideCompanyDropdown() {
    setTimeout(() => {
        showCompanyDropdown.value = false;
    }, 200);
}

function hideContactDropdown() {
    setTimeout(() => {
        showContactDropdown.value = false;
    }, 200);
}

function hideMaterialDropdown() {
    setTimeout(() => {
        showMaterialDropdown.value = false;
    }, 200);
}

// 选择公司
async function selectCompany(company: Company) {
    selectedCompany.value = company;
    order.value.client_id = company.id;
    order.value.customer_name = company.name;
    companySearchText.value = company.name;

    // 重置选中的联系人
    selectedContact.value = null;
    order.value.contact_id = 0;
    order.value.contact_name = "";
    contactSearchText.value = "";

    // 获取该公司的联系人
    await fetchContactsByCompany(company.id);

    hideCompanyDropdown();
}

// 选择材料
function selectMaterial(material: Material) {
    selectedMaterial.value = material;
    order.value.material_id = material.id || 0;
    order.value.material_name = material.name;
    order.value.material_code = material.code;
    materialSearchText.value = material.name || "";

    // 设置材料价格（需要除以10000）
    if (material.price) {
        setPrice(material.price / 10000);
    }
    // 设置材料单位
    if (material.unit) {
        order.value.unit = material.unit;
    }

    hideMaterialDropdown();
}

// 选择联系人
function selectContact(contact: Contact) {
    selectedContact.value = contact;
    order.value.contact_id = contact.id;
    order.value.contact_name = contact.name;
    contactSearchText.value = contact.name;

    hideContactDropdown();
}

// 从日期时间字符串中提取日期部分 - 参考日历组件
function extractDateFromDateTime(dateTimeStr: string): string {
    if (!dateTimeStr) return "";

    try {
        // 处理不同的日期时间格式
        let date: Date;

        if (dateTimeStr.includes("T")) {
            // ISO 格式：2024-01-01T08:00:00
            date = new Date(dateTimeStr);
        } else if (dateTimeStr.includes(" ")) {
            // 空格分隔格式：2024-01-01 08:00:00
            date = new Date(dateTimeStr.replace(" ", "T"));
        } else {
            // 只有日期
            return dateTimeStr;
        }

        if (isNaN(date.getTime())) {
            console.warn("Invalid date:", dateTimeStr);
            return "";
        }

        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    } catch (e) {
        console.error("Error parsing date:", e, dateTimeStr);
        return "";
    }
}

// 获取订单详情
async function fetchOrderDetail() {
    if (!orderId.value) return;

    loading.value = true;
    error.value = "";

    try {
        const response: ApiResponse<Order> = await invoke("order_detail", {
            order_id: orderId.value,
        });

        if (response.status_code === 200 && response.data) {
            order.value = response.data;

            // 格式化日期字段为 yyyy-MM-dd
            order.value.place_order_date = extractDateFromDateTime(
                response.data.place_order_date,
            );
            order.value.plan_delivery_date = extractDateFromDateTime(
                response.data.plan_delivery_date,
            );
            if (response.data.actual_delivery_date) {
                order.value.actual_delivery_date = extractDateFromDateTime(
                    response.data.actual_delivery_date,
                );
            }

            selectedCompany.value = null;
            selectedMaterial.value = null;
            selectedContact.value = null;

            // 设置公司
            if (response.data.client_id) {
                const company = companies.value.find(
                    (c) => c.id === response.data.client_id,
                );
                if (company) {
                    selectedCompany.value = company;
                    companySearchText.value = company.name;

                    // 加载联系人
                    await fetchContactsByCompany(company.id);

                    // 设置联系人（必须在联系人加载后）
                    if (response.data.contact_id) {
                        const contact = contacts.value.find(
                            (c) => c.id === response.data.contact_id,
                        );
                        if (contact) {
                            selectedContact.value = contact;
                            contactSearchText.value = contact.name;
                        }
                    }
                }
            }

            // 设置材料
            if (response.data.material_id) {
                const material = materials.value.find(
                    (m) => m.id === response.data.material_id,
                );
                if (material) {
                    selectedMaterial.value = material;
                    materialSearchText.value = material.name || "";
                }
            }

            success.value = "订单详情加载成功";
        } else {
            error.value = response.message || "获取订单详情失败";
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("获取订单详情失败:", err);
    } finally {
        loading.value = false;
    }
}

// 进入编辑模式
function enterEditMode() {
    isEditMode.value = true;

    // 确保搜索框显示正确文本，优先使用 selected，否则 fallback 到 order.value
    companySearchText.value =
        selectedCompany.value?.name || order.value.customer_name || "";
    contactSearchText.value =
        selectedContact.value?.name || order.value.contact_name || "";
    materialSearchText.value =
        selectedMaterial.value?.name || order.value.material_name || "";
}

// 取消编辑
function cancelEdit() {
    isEditMode.value = false;
    // 重置表单数据
    if (orderId.value) {
        fetchOrderDetail();
    } else {
        order.value = createEmptyOrder();
        selectedCompany.value = null;
        selectedMaterial.value = null;
        selectedContact.value = null;
        contacts.value = [];
        companySearchText.value = "";
        contactSearchText.value = "";
        materialSearchText.value = "";
        filteredCompanies.value = [];
        filteredContacts.value = [];
        filteredMaterials.value = [];
    }
    error.value = "";
    success.value = "";
}

// 创建或更新订单
async function saveOrder() {
    if (!order.value.client_id) {
        error.value = "请选择客户";
        return;
    }

    if (!order.value.material_id) {
        error.value = "请选择材料";
        return;
    }

    if (order.value.quantity <= 0) {
        error.value = "数量必须大于0";
        return;
    }

    if (order.value.price <= 0) {
        error.value = "价格必须大于0";
        return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        // 准备订单数据，确保所有必需字段都有值
        let actual_delivery_date = null;
        if (order.value.actual_delivery_date) {
            actual_delivery_date =
                order.value.actual_delivery_date + "T00:00:00";
        }

        const orderData = {
            id: order.value.id,
            material_id: order.value.material_id,
            client_id: order.value.client_id,
            contact_id: order.value.contact_id,
            quantity: order.value.quantity,
            price: order.value.price,
            amount: order.value.amount,
            unit: order.value.unit,
            place_order_date: order.value.place_order_date + "T00:00:00",
            plan_delivery_date: order.value.plan_delivery_date + "T00:00:00",
            actual_delivery_date: actual_delivery_date,
            status: order.value.status,
            remark: order.value.remark || "",
            image_path: order.value.image_path,
            customer_name: order.value.customer_name || "",
            customer_code: order.value.customer_code || "",
            material_name: order.value.material_name || "",
            material_code: order.value.material_code || "",
            contact_name: order.value.contact_name || "",
        };

        console.log("Sending order data:", orderData);

        let response: ApiResponse<Order>;

        if (order.value.id === 0) {
            // 创建订单
            response = await invoke("create_order", {
                data: JSON.stringify(orderData),
            });
        } else {
            // 更新订单
            response = await invoke("update_order", {
                data: JSON.stringify(orderData),
            });
        }

        if (response.status_code === 200) {
            if (response.data) {
                order.value = response.data;
                // 格式化返回的日期
                order.value.place_order_date = extractDateFromDateTime(
                    response.data.place_order_date,
                );
                order.value.plan_delivery_date = extractDateFromDateTime(
                    response.data.plan_delivery_date,
                );
                if (response.data.actual_delivery_date) {
                    order.value.actual_delivery_date = extractDateFromDateTime(
                        response.data.actual_delivery_date,
                    );
                }
            }
            success.value =
                order.value.id === 0 ? "订单创建成功" : "订单更新成功";
            isEditMode.value = false;

            // 如果是创建订单，更新URL
            if (order.value.id !== 0 && !orderId.value) {
                window.history.replaceState({}, "", `/order/${order.value.id}`);
            }
        } else {
            error.value = response.message || "保存订单失败";
        }
    } catch (err) {
        error.value = "网络请求失败: " + err;
        console.error("保存订单失败:", err);
    } finally {
        loading.value = false;
    }
}
// 删除订单（软删除，更新状态为0）
async function deleteOrder() {
    if (!orderId.value) return;

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        const response = await invoke("update_order", {
            data: JSON.stringify({
                ...order.value,
                status: 0, // 设置为0表示作废
            }),
        });

        success.value = "订单删除成功！";
        showDeleteConfirm.value = false;

        // 2秒后返回订单列表
        setTimeout(() => {
            router.back();
        }, 2000);
    } catch (err) {
        error.value = "删除订单失败：" + err;
        console.error("删除订单失败:", err);
        showDeleteConfirm.value = false;
    } finally {
        loading.value = false;
    }
}

// 显示删除确认对话框
function confirmDelete() {
    showDeleteConfirm.value = true;
}

// 取消删除
function cancelDelete() {
    showDeleteConfirm.value = false;
}

// 返回上一页
function goBack() {
    router.back();
}

// 获取状态标签
function getStatusLabel(status: number): string {
    const statusOption = statusOptions.find((opt) => opt.value === status);
    return statusOption ? statusOption.label : "未知状态";
}

// 获取状态徽章类
function getStatusBadge(status: number): string {
    const badgeClasses: Record<number, string> = {
        0: "badge-error",
        1: "badge-info",
        2: "badge-success",
        3: "badge-warning",
        4: "badge-primary",
        5: "badge-secondary",
        6: "badge-accent",
        7: "badge-neutral",
        8: "badge-success",
        9: "badge-warning",
        10: "badge-success",
        11: "badge-error",
        12: "badge-warning",
        13: "badge-info",
        14: "badge-error",
    };
    return badgeClasses[status] || "badge-neutral";
}

// 获取公司类型标签
function getCompanyTypeLabel(typeId: number): string {
    const typeOption = companyTypeOptions.find((opt) => opt.value === typeId);
    return typeOption ? typeOption.label : "未知类型";
}

// 获取公司状态标签
function getCompanyStatusLabel(status: number): string {
    const statusOption = companyStatusOptions.find(
        (opt) => opt.value === status,
    );
    return statusOption ? statusOption.label : "未知状态";
}

// 获取联系人状态标签
function getContactStatusLabel(status: number): string {
    const statusOption = contactStatusOptions.find(
        (opt) => opt.value === status,
    );
    return statusOption ? statusOption.label : "未知状态";
}

// 格式化日期时间
function formatDateTime(dateTime: string | null): string {
    if (!dateTime) return "无";
    return extractDateFromDateTime(dateTime);
}

// 格式化日期
function formatDate(dateTime: string | null): string {
    if (!dateTime) return "无";
    return extractDateFromDateTime(dateTime);
}

// 页面加载时初始化
onMounted(async () => {
    await fetchCompanies();
    await fetchMaterials();

    if (orderId.value) {
        await fetchOrderDetail();
    } else {
        // 新建订单时默认为编辑模式
        isEditMode.value = true;
    }
});

// 监听路由变化
watch(
    () => route.params.id,
    (newId) => {
        if (newId) {
            fetchOrderDetail();
        } else {
            order.value = createEmptyOrder();
            selectedCompany.value = null;
            selectedMaterial.value = null;
            selectedContact.value = null;
            contacts.value = [];
            companySearchText.value = "";
            contactSearchText.value = "";
            materialSearchText.value = "";
            filteredCompanies.value = [];
            filteredContacts.value = [];
            filteredMaterials.value = [];
            isEditMode.value = true;
        }
    },
);
</script>

<template>
    <main class="container mx-auto p-4 max-w-4xl">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">
                {{
                    isEditMode
                        ? order.id === 0
                            ? "创建订单"
                            : "编辑订单"
                        : "订单详情"
                }}
            </h1>
            <div class="flex gap-2" v-if="!isEditMode && order.id !== 0">
                <button @click="enterEditMode" class="btn btn-primary">
                    编辑
                </button>
                <button @click="confirmDelete" class="btn btn-error">
                    删除
                </button>
                <button @click="goBack" class="btn btn-outline">返回</button>
            </div>
        </div>

        <!-- 成功提示 -->
        <div v-if="success" class="alert alert-success mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M8.5 11.5 11 14l4-4m6 2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ success }}</span>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="alert alert-error mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 13V8m0 8h0m9-4a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ error }}</span>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="text-center p-8">
            <span class="loading loading-spinner loading-lg"></span>
            <p class="mt-2">加载中...</p>
        </div>

        <div
            v-else
            class="bg-base-100 rounded-lg shadow-sm border border-gray-200"
        >
            <!-- 客户信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    客户信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 客户名称 -->
                    <div class="form-control relative">
                        <label class="label">
                            <span class="label-text font-medium">客户名称</span>
                        </label>
                        <div v-if="isEditMode">
                            <input
                                v-model="companySearchText"
                                type="text"
                                placeholder="输入公司名称搜索..."
                                class="input input-bordered w-full"
                                @input="handleCompanySearch"
                                @focus="showCompanyDropdown = true"
                                @blur="hideCompanyDropdown"
                            />
                            <!-- 公司下拉列表 -->
                            <div
                                v-if="showCompanyDropdown"
                                class="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto"
                            >
                                <div
                                    v-if="companyLoading"
                                    class="p-2 text-center"
                                >
                                    <span
                                        class="loading loading-spinner loading-sm"
                                    ></span>
                                    搜索中...
                                </div>
                                <div
                                    v-else-if="
                                        !filteredCompanies ||
                                        filteredCompanies.length === 0
                                    "
                                    class="p-2 text-gray-500"
                                >
                                    {{
                                        companySearchText
                                            ? "未找到匹配的公司"
                                            : "输入公司名称进行搜索"
                                    }}
                                </div>
                                <div v-else>
                                    <div
                                        v-for="company in filteredCompanies"
                                        :key="company.id"
                                        class="p-2 hover:bg-gray-100 cursor-pointer border-b border-gray-100"
                                        @click="selectCompany(company)"
                                    >
                                        <div class="font-medium">
                                            {{ company.name }}
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            {{
                                                getCompanyTypeLabel(
                                                    company.type_id,
                                                )
                                            }}
                                            ·
                                            {{
                                                getCompanyStatusLabel(
                                                    company.status,
                                                )
                                            }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ order.customer_name || "未选择" }}
                        </div>
                    </div>

                    <!-- 客户类型 -->
                    <div class="form-control" v-if="selectedCompany">
                        <label class="label">
                            <span class="label-text font-medium">客户类型</span>
                        </label>
                        <div class="p-2 border rounded-md bg-gray-50">
                            {{ getCompanyTypeLabel(selectedCompany.type_id) }}
                        </div>
                    </div>

                    <!-- 联系人 -->
                    <div class="form-control relative">
                        <label class="label">
                            <span class="label-text font-medium">联系人</span>
                        </label>
                        <div v-if="isEditMode">
                            <input
                                v-model="contactSearchText"
                                type="text"
                                placeholder="输入联系人姓名搜索..."
                                class="input input-bordered w-full"
                                :disabled="!selectedCompany"
                                @input="handleContactSearch"
                                @focus="showContactDropdown = true"
                                @blur="hideContactDropdown"
                            />
                            <!-- 联系人下拉列表 -->
                            <div
                                v-if="showContactDropdown && selectedCompany"
                                class="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto"
                            >
                                <div
                                    v-if="contactLoading"
                                    class="p-2 text-center"
                                >
                                    <span
                                        class="loading loading-spinner loading-sm"
                                    ></span>
                                    搜索中...
                                </div>
                                <div
                                    v-else-if="
                                        !filteredContacts ||
                                        filteredContacts.length === 0
                                    "
                                    class="p-2 text-gray-500"
                                >
                                    {{
                                        contactSearchText
                                            ? "未找到匹配的联系人"
                                            : "输入联系人姓名进行搜索"
                                    }}
                                </div>
                                <div v-else>
                                    <div
                                        v-for="contact in filteredContacts"
                                        :key="contact.id"
                                        class="p-2 hover:bg-gray-100 cursor-pointer border-b border-gray-100"
                                        @click="selectContact(contact)"
                                    >
                                        <div class="font-medium">
                                            {{ contact.name }}
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            {{ contact.phone || "无电话" }} ·
                                            {{ contact.job_title || "无职位" }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div
                                v-if="!selectedCompany"
                                class="text-sm text-warning mt-1"
                            >
                                请先选择客户
                            </div>
                        </div>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ order.contact_name || "未选择" }}
                        </div>
                    </div>

                    <!-- 联系人电话 -->
                    <div class="form-control" v-if="selectedContact">
                        <label class="label">
                            <span class="label-text font-medium"
                                >联系人电话</span
                            >
                        </label>
                        <div class="p-2 border rounded-md bg-gray-50">
                            {{ selectedContact.phone || "无" }}
                        </div>
                    </div>

                    <!-- 下单时间 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">下单时间</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="order.place_order_date"
                            type="date"
                            class="input input-bordered"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ formatDateTime(order.place_order_date) }}
                        </div>
                    </div>

                    <!-- 计划交付时间 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >计划交付时间</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="order.plan_delivery_date"
                            type="date"
                            class="input input-bordered"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ formatDateTime(order.plan_delivery_date) }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 材料信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    材料信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 材料 -->
                    <div class="form-control relative">
                        <label class="label">
                            <span class="label-text font-medium">材料</span>
                        </label>
                        <div v-if="isEditMode">
                            <input
                                v-model="materialSearchText"
                                type="text"
                                placeholder="输入材料名称或代码搜索..."
                                class="input input-bordered w-full"
                                @input="handleMaterialSearch"
                                @focus="showMaterialDropdown = true"
                                @blur="hideMaterialDropdown"
                            />
                            <!-- 材料下拉列表 -->
                            <div
                                v-if="showMaterialDropdown"
                                class="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto"
                            >
                                <div
                                    v-if="materialLoading"
                                    class="p-2 text-center"
                                >
                                    <span
                                        class="loading loading-spinner loading-sm"
                                    ></span>
                                    搜索中...
                                </div>
                                <div
                                    v-else-if="
                                        !filteredMaterials ||
                                        filteredMaterials.length === 0
                                    "
                                    class="p-2 text-gray-500"
                                >
                                    {{
                                        materialSearchText
                                            ? "未找到匹配的材料"
                                            : "输入材料名称或代码进行搜索"
                                    }}
                                </div>
                                <div v-else>
                                    <div
                                        v-for="material in filteredMaterials"
                                        :key="material.id || 0"
                                        class="p-2 hover:bg-gray-100 cursor-pointer border-b border-gray-100"
                                        @click="selectMaterial(material)"
                                    >
                                        <div class="font-medium">
                                            {{ material.name || "未命名" }}
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            代码: {{ material.code || "无" }} ·
                                            价格:
                                            {{
                                                material.price
                                                    ? (
                                                          material.price / 10000
                                                      ).toFixed(2)
                                                    : "无"
                                            }}
                                            {{ material.unit || "" }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ order.material_name || "未选择" }}
                        </div>
                    </div>

                    <!-- 材料代码 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">材料代码</span>
                        </label>
                        <div class="p-2 border rounded-md bg-gray-50">
                            {{ order.material_code || "无" }}
                        </div>
                    </div>

                    <!-- 数量 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">数量</span>
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model.number="order.quantity"
                            type="number"
                            class="input input-bordered"
                            min="0"
                            step="1"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ order.quantity }}
                        </div>
                    </div>

                    <!-- 单价 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">单价</span>
                        </label>
                        <div v-if="isEditMode" class="flex gap-2">
                            <input
                                :value="getDisplayPrice()"
                                @input="
                                    setPrice(
                                        parseFloat(
                                            ($event.target as HTMLInputElement)
                                                .value,
                                        ) || 0,
                                    )
                                "
                                type="number"
                                step="0.01"
                                class="input input-bordered flex-1"
                                placeholder="价格"
                            />
                            <select
                                v-model="order.unit"
                                class="select select-bordered w-28"
                            >
                                <option
                                    v-for="unit in unitOptions"
                                    :key="unit.value"
                                    :value="unit.value"
                                >
                                    {{ unit.label }}
                                </option>
                            </select>
                        </div>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ getDisplayPrice() }} {{ order.unit }}
                        </div>
                        <div
                            class="text-xs text-gray-500 mt-1"
                            v-if="isEditMode"
                        >
                            存储值: {{ order.price }} (显示值 × 10000)
                        </div>
                    </div>

                    <!-- 总价 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">总价</span>
                        </label>
                        <div class="p-2 border rounded-md bg-gray-50">
                            {{ totalAmount }} {{ order.unit }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 订单状态 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    订单状态
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 状态 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">状态</span>
                        </label>
                        <select
                            v-if="isEditMode"
                            v-model="order.status"
                            class="select select-bordered"
                        >
                            <option
                                v-for="status in statusOptions"
                                :key="status.value"
                                :value="status.value"
                            >
                                {{ status.label }}
                            </option>
                        </select>
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            <span
                                :class="['badge', getStatusBadge(order.status)]"
                            >
                                {{ getStatusLabel(order.status) }}
                            </span>
                        </div>
                    </div>

                    <!-- 实际交付时间 -->
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >实际交付时间</span
                            >
                        </label>
                        <input
                            v-if="isEditMode"
                            v-model="order.actual_delivery_date"
                            type="date"
                            class="input input-bordered"
                        />
                        <div v-else class="p-2 border rounded-md bg-gray-50">
                            {{ formatDateTime(order.actual_delivery_date) }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 备注信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    备注信息
                </h3>
                <div class="form-control">
                    <textarea
                        v-if="isEditMode"
                        v-model="order.remark"
                        class="textarea textarea-bordered h-24"
                        placeholder="请输入订单备注..."
                    ></textarea>
                    <div
                        v-else
                        class="p-3 border rounded-md bg-gray-50 min-h-24"
                    >
                        {{ order.remark || "无备注" }}
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑模式下的操作按钮 -->
        <div class="flex justify-end gap-3 mt-6" v-if="isEditMode">
            <button
                type="button"
                @click="cancelEdit"
                class="btn btn-outline"
                :disabled="loading"
            >
                取消
            </button>
            <button
                type="button"
                @click="saveOrder"
                class="btn btn-primary"
                :disabled="loading"
            >
                <span
                    v-if="loading"
                    class="loading loading-spinner loading-sm"
                ></span>
                {{ order.id === 0 ? "创建订单" : "保存" }}
            </button>
        </div>

        <!-- 删除确认对话框 -->
        <div v-if="showDeleteConfirm" class="modal modal-open">
            <div class="modal-box">
                <h3 class="font-bold text-lg">确认删除</h3>
                <p class="py-4">
                    确定要删除订单 #{{ order.id }} 吗？此操作不可逆。
                </p>
                <div class="modal-action">
                    <button
                        @click="cancelDelete"
                        class="btn btn-outline"
                        :disabled="loading"
                    >
                        取消
                    </button>
                    <button
                        @click="deleteOrder"
                        class="btn btn-error"
                        :disabled="loading"
                    >
                        <span
                            v-if="loading"
                            class="loading loading-spinner loading-sm"
                        ></span>
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </main>
</template>

<style scoped>
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}
</style>
